Skip to content

fix(ndb): resolve universe_domain and validate credentials in Client - #19251

Open
ohmayr wants to merge 3 commits into
mainfrom
smallpr/b589768754-ndb-universe-domain
Open

ohmayr wants to merge 3 commits into
mainfrom
smallpr/b589768754-ndb-universe-domain

Conversation

@ohmayr

@ohmayr ohmayr commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Context & Problem

google.cloud.ndb.Client ignored client_options.universe_domain and GOOGLE_CLOUD_UNIVERSE_DOMAIN, hardcoding datastore.googleapis.com and opening a gRPC channel without validating credential universe parity (AIP-4113).

Summary of Changes

  • Resolve universe_domain in ndb.Client.init via google.api_core.universe.determine_domain and expose client.universe_domain.
  • Template the default Datastore endpoint as datastore.<universe_domain> when client_options.api_endpoint and DATASTORE_EMULATOR_HOST are unset.
  • Validate credential universe parity via _validate_credentials_universe before opening a secure gRPC channel (exempting emulator mode, AnonymousCredentials, uncached compute_engine.Credentials, and non-string credential mocks).
  • Add unit tests covering client_options, GOOGLE_CLOUD_UNIVERSE_DOMAIN, endpoint precedence, empty universe errors, mismatch errors before channel creation, and exemptions, and clear GOOGLE_CLOUD_UNIVERSE_DOMAIN in unit test conftest.

Why This Approach

Resolving universe_domain and validating credentials directly inside ndb.Client.init before make_secure_channel prevents cross-universe token leakage while preserving google-cloud-ndb's google-api-core >= 2.28.0 lower bound. We considered waiting for google.api_core.universe.validate_credentials_universe (> 2.44.0) or relying on google-cloud-core, but mirroring _validate_credentials_universe locally with a TODO(universe-domain) marker matches sibling PRs (#19192, #19231) and works immediately without bumping dependency floors.

Intentionally Out of Scope

  • Bumping google-api-core minimum version in setup.py or testing/constraints-3.10.txt.
  • Changing DatastoreGrpcTransport or google-cloud-datastore client behavior (tracked separately in b/588887217).
  • Refactoring unrelated ndb.Client attributes or removing DATASTORE_API_HOST.

Verification

pytest packages/google-cloud-ndb/tests/unit/ on Python 3.14 with google-api-core==2.28.0 (1851 passed, including 16 new universe_domain tests in test_client.py)

Fixes: b/589768754

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds universe domain support and validation to the Google Cloud NDB client, resolving the universe domain from client options or environment variables and templating the API endpoint. A critical issue was identified in the _validate_credentials_universe helper function, where universe.compare_domains is incorrectly called with a Credentials object instead of a domain string, and its return value is not checked to raise a UniverseMismatchError on mismatch.

@ohmayr ohmayr changed the title fix(google-cloud-ndb): respect universe_domain and validate credentials fix(ndb): resolve universe_domain and validate credentials in Client Nov 27, 2026
Resolve universe_domain via google.api_core.universe.determine_domain,
template the default Datastore host as datastore.<universe_domain>, and
validate credential universe parity before opening a secure gRPC channel
(AIP-4113).

Fixes: b/589768754
@ohmayr
ohmayr force-pushed the smallpr/b589768754-ndb-universe-domain branch from 7d3f485 to 6f851f4 Compare November 27, 2026 18:24
Remove the fail-open non-string universe_domain bypass in
_validate_credentials_universe so it delegates directly to
universe.compare_domains and matches google-api-core, accept any
Mapping in Client.__init__ via client_options.from_dict, and fall back
to api_endpoint when DATASTORE_EMULATOR_HOST is an empty string.

Fix tests/conftest.py unit-module prefix matching so ambient
GOOGLE_CLOUD_UNIVERSE_DOMAIN is cleared under pytest, set
universe_domain on patch_credentials, and expand test_client.py
assertions and edge-case coverage.
@ohmayr
ohmayr marked this pull request as ready for review December 2, 2026 00:49
@ohmayr
ohmayr requested a review from a team as a code owner December 2, 2026 00:49

@chalmerlowe chalmerlowe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some suggestions, please take a look.

Comment on lines +411 to +416
with _patch_secure_channel() as make_channel:
client = client_module.Client(
project="testing",
credentials=creds,
client_options=ClientOptions(universe_domain="tpc.test"),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Patching compute_engine.Credentials.universe_domain here ensures the test fails loudly if universe_domain is ever accessed accidentally during init:

Suggested change
with _patch_secure_channel() as make_channel:
client = client_module.Client(
project="testing",
credentials=creds,
client_options=ClientOptions(universe_domain="tpc.test"),
)
with (
mock.patch.object(
compute_engine.Credentials,
"universe_domain",
new_callable=mock.PropertyMock,
side_effect=AssertionError("MDS must not be queried during init"),
),
_patch_secure_channel() as make_channel,
):
client = client_module.Client(
project="testing",
credentials=creds,
client_options=ClientOptions(universe_domain="tpc.test"),
)

Comment on lines +475 to +476
(ClientOptions(universe_domain=" opts.test "), None, "opts.test"),
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest we also add these two precedence cases so explicit "googleapis.com" overriding GOOGLE_CLOUD_UNIVERSE_DOMAIN and an unset ClientOptions() falling back to the env var are covered?

Suggested change
(ClientOptions(universe_domain=" opts.test "), None, "opts.test"),
],
(ClientOptions(universe_domain=" opts.test "), None, "opts.test"),
({"universe_domain": "googleapis.com"}, "env.test", "googleapis.com"),
(ClientOptions(), "env.test", "env.test"),
],

Comment on lines +82 to +92
def _validate_credentials_universe(client_universe, credentials):
"""Validate that resolved client credentials match ``client_universe``."""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
# Avoid synchronous GCE metadata server HTTP calls when
# compute_engine.Credentials hasn't resolved its universe yet.
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
universe.compare_domains(client_universe, credentials)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a look at the code in the catalog and the most recent version seems more robust (more robust docstrings, typehints, etc):

Suggested change
def _validate_credentials_universe(client_universe, credentials):
"""Validate that resolved client credentials match ``client_universe``."""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
# Avoid synchronous GCE metadata server HTTP calls when
# compute_engine.Credentials hasn't resolved its universe yet.
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
universe.compare_domains(client_universe, credentials)
def validate_credentials_universe(
client_universe: str,
credentials: Any,
) -> None:
"""Validate that resolved client credentials match ``client_universe``.
Call on ``self._credentials`` after ``super().__init__()`` or Application
Default Credentials resolution rather than on the raw constructor
``credentials`` argument (which is ``None`` before ADC loads), and never
inside ``Credentials.before_request()``. Exempts ``None``, synchronous and
asynchronous ``AnonymousCredentials``, and ``compute_engine.Credentials``
whose universe domain is not yet cached in memory (avoiding synchronous
Metadata Server HTTP requests during client initialization).
Args:
client_universe: Resolved universe domain of the client.
credentials: Resolved credentials bound to the client, or ``None`` (in
which case validation is skipped).
Raises:
google.api_core.universe.UniverseMismatchError: If ``credentials`` has
an in-memory universe domain configured for a different universe
than ``client_universe``.
"""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
universe.compare_domains(client_universe, credentials)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants